﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;

namespace Microsoft.WindowsPhone.ChineseInput.InputProviders
{
    public class BaiduCloudInput : CloudInputInterface
    {
        public event EventHandler<CloudInputResponseEventArgs> ResponseReceived;

        public void SendRequest(string text)
        {
            WebClient client = new WebClient();

            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            client.DownloadStringAsync(
                new Uri("http://olime.baidu.com/py?py=" + text + "&rn=0&pn=20"));
        }

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            // FIXME:Encoding GBK 
            Regex regex = new Regex("\\[\"(.+),\\d+\"\\]");
            var matches = regex.Match(e.Result);

            List<string> candidates = new List<string>();

            for (int i = 1; i < matches.Groups.Count; i++)
            {
                var text = matches.Groups[i].Value;
                candidates.Add(text);
            }

            if (ResponseReceived != null)
            {
                ResponseReceived(this, new CloudInputResponseEventArgs() { Candidates = candidates });
            }
        }
    }
}
